package org.jarraiders.musiclibrary.client.presenter;

import org.jarraiders.musiclibrary.client.TracksServiceAsync;
import org.jarraiders.musiclibrary.client.event.EditTrackCancelledEvent;
import org.jarraiders.musiclibrary.client.event.TrackUpdatedEvent;
import org.jarraiders.musiclibrary.shared.domain.TrackDTO;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

public class EditTrackPresenter implements Presenter {
	public interface Display {
		HasClickHandlers getSaveButton();

		HasClickHandlers getCancelButton();

		HasValue<String> getTrackName();

		HasValue<String> getTrackNumber();

		Widget asWidget();
	}

	private TrackDTO track;
	private final TracksServiceAsync rpcService;
	private final HandlerManager eventBus;
	private final Display display;

	public EditTrackPresenter(TracksServiceAsync rpcService, HandlerManager eventBus, Display display) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.track = new TrackDTO();
		this.display = display;
		bind();
	}

	public EditTrackPresenter(TracksServiceAsync rpcService, HandlerManager eventBus, Display display, String id) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;
		bind();

		rpcService.getTrack(id, new AsyncCallback<TrackDTO>() {
			public void onSuccess(TrackDTO result) {
				track = result;
				EditTrackPresenter.this.display.getTrackName().setValue(track.getTrackTitle());
				EditTrackPresenter.this.display.getTrackNumber().setValue(track.getTrackNumber()+"");

			}

			public void onFailure(Throwable caught) {
				Window.alert("Error retrieving contact");
			}
		});

	}

	public void bind() {
		this.display.getSaveButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				doSave();
			}
		});

		this.display.getCancelButton().addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new EditTrackCancelledEvent());
			}
		});
	}

	@Override
	public void go(final HasWidgets container) {
		container.clear();
		container.add(display.asWidget());
	}

	private void doSave() {
		track.setTrackTitle(display.getTrackName().getValue());
		track.setTrackNumber(new Integer(display.getTrackNumber().getValue()));
		

		rpcService.updateTrack(track, new AsyncCallback<TrackDTO>() {
			public void onSuccess(TrackDTO result) {
				eventBus.fireEvent(new TrackUpdatedEvent(result));
			}

			public void onFailure(Throwable caught) {
				Window.alert("Error updating contact");
			}
		});
	}

}
